import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'date_result.dart';

class Result extends DateResult<String> {
  bool isSuccess;
  int code;
  String data;
  String message;
  Result({this.isSuccess, this.code, this.message, this.data}):super(isSuccess:isSuccess,code:code,message:message,data:data);
  @override
  String toString() {
    // TODO: implement toString
    return 'isSuccess:${this.isSuccess},code:${this.code},message:${this.message},data:${this.data}';
  }
}







/// 单例 DioUtil.
/// debug模式下可以打印请求日志. DioUtil.openDebug().
/// dio详细使用请查看dio官网(https://github.com/flutterchina/dio).
class DioUtil {
  static DioUtil _single;

  Dio _dio;

  static DioUtil getInstance() {
    return DioUtil._init() ;
  }

  DioUtil._init() {
    _dio = createDio();
  }

  /// 打开debug模式.

  Dio createDio() {
    Dio dio =  Dio(getDefBaseOptions());
    dio.interceptors
        .add(InterceptorsWrapper(onRequest: (RequestOptions options) {
      printRequest(options);
      return options;
    }, onResponse: (Response reponse) {
      printResponse(reponse);

      return reponse;
    }, onError: (DioError e) {
      return e;
    }));

    return dio;
  }

  void printRequest(RequestOptions options) {
    StringBuffer sb = StringBuffer();
    sb.writeln('===============Start Request========================');
    sb.writeln('${options.baseUrl}${options.path}');
    sb.writeln('queryParameters = ${options.queryParameters.toString()}');
    sb.writeln('data = ${options.data.toString()}');
    sb.write('=================end   Request========================');
    print(sb.toString());
  }

  void printResponse(Response reponse) {
    StringBuffer sb = StringBuffer();
    sb.writeln('===============Start Response========================');
    sb.writeln('statusCode = ${reponse.statusCode}');
    sb.writeln('data = ${reponse.data}');
    sb.writeln('all = ${reponse.toString()}');
    sb.write('=================end   Response========================');
    print(sb.toString());
  }



  /// decode response data.
  Map<String, dynamic> _decodeData(Response response) {
    if (response == null ||
        response.data == null ||
        response.data.toString().isEmpty) {
      return new Map();
    }
    return json.decode(response.data.toString());
  }

  static BaseOptions getDefBaseOptions() {
    BaseOptions options = new BaseOptions();

    options.contentType =
        ContentType.parse("application/x-www-form-urlencoded");
    options.connectTimeout = 1000 * 10;
    options.receiveTimeout = 1000 * 20;
    options.responseType = ResponseType.plain;
    options.maxRedirects = 3;
    return options;
  }

  static Future<Result> post(String path,
      {Map<String, dynamic> data,
      Map<String, dynamic> queryParameters,
      CancelToken cancelToken}) async {
    Result result;
    try {
      Response response = await getInstance()._dio.post(path,
          data: data,
          queryParameters: queryParameters,
          cancelToken: cancelToken);
      result = Result(isSuccess: response.statusCode ==200 ? true:false,code: response.statusCode,data: response.data);
    } catch (e) {
      print('post catch,message=${e.toString()}');
      result = Result(isSuccess: false, message: e.toString(),code: e.hashCode);
    }

    return result;
  }

  static  Future<Result> get(String path,
      {Map<String, dynamic> queryParameters, CancelToken cancelToken}) async {
    Result result;
    try {
      Response response = await getInstance()._dio.get(path,
          queryParameters: queryParameters, cancelToken: cancelToken);
      result = Result(isSuccess: response.statusCode ==200 ? true:false,code: response.statusCode,data: response.data);
    } catch (e) {
      result = Result(isSuccess: false, message: e.toString());
    }

    return result;
  }
}
